<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>在线聊天室</title>
</head>

<body>
  <input type="text" id="text">
  <input type="button" value="发送" id="btn">
  <script src="https://cdn.bootcss.com/socket.io/2.1.1/socket.io.slim.js"></script>
  <script>
    var oText = document.getElementById('text');
    var oBtn = document.getElementById('btn');

    var socket = io.connect('http://localhost:3000/');
    oBtn.onclick = function () {
      var val = oText.value;
      // 通过实例发送val消息
      // socket.send(val);
      socket.emit('messages', val);
      oText.value = '';
    };
    socket.on('message', function (data) {
      var p = document.createElement('p');
      p.innerText = data;
      document.body.appendChild(p);
    });
  </script>
</body>

</html>